package com.tanhua.server.service;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.VisitorsApi;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.pojo.Visitors;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.pojo.User;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.utils.RelativeDateFormat;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.Movements;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.PicUploadResult;
import com.tanhua.server.vo.VisitorsVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class MovementsService {

    /*@Autowired
    private UserService userService;*/

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    @Autowired
    private PicUploadService picUploadService;

    @Autowired
    private UserInfoService userInfoService;

    /**
     * 保存发布状态
     *
     * @param textContent
     * @param location
     * @param latitude
     * @param longitude
     * @param multipartFile
     * @param //token
     * @return
     */
    public String savePublish(String textContent, String location,
                              String latitude, String longitude,
                              MultipartFile[] multipartFile) {
        // 查询用户当前登录状态
        /*User user = this.userService.queryUserByToken(token);
        if(null == user){
            return false;
        }*/
        User user = UserThreadLocal.get();
        // 把前台传递过来的数据封装到publish对象中
        Publish publish = new Publish();
        publish.setUserId(user.getId());  //用户id
        publish.setText(textContent);
        publish.setLocationName(location);
        publish.setLatitude(latitude);
        publish.setLongitude(longitude);
        publish.setSeeType(1);    //公开类型
        //图片保存正常存到对象中的要为链接，实际是在这里存到阿里的oss中
        // 集合保存存放图片路径
        List<String> picUrls = new ArrayList<>();
        for (MultipartFile file : multipartFile) {
            PicUploadResult upload = this.picUploadService.upload(file);
            picUrls.add(upload.getName());
        }
        publish.setMedias(picUrls);
        // 调用quanziapi进行publish保存
        return quanZiApi.savePublish(publish);
    }

    /**
     * 查询圈子动态
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryPublishList(Integer page, Integer pageSize, boolean recommendBool) {
        PageResult pageResult = new PageResult();
        //获取当前的登录信息
        User user = UserThreadLocal.get();
        Long userId = user.getId();
        if (recommendBool) {
            userId = null;
        }

        PageInfo<Publish> pageInfo = null;
        // 如果查询的是推荐
        if (null == userId) {
            // 从大数据推荐中拿数据
            String value = this.redisTemplate.opsForValue().get("QUANZI_PUBLISH_RECOMMEND_" + user.getId());
            if (null != value) {
                String[] pids = StringUtils.split(value, ",");
                // 分页设置
                int startIndex = (page - 1) * pageSize;
                if (startIndex < pids.length) {
                    int endIndex = startIndex + pageSize - 1;
                    if (endIndex >= pids.length) {
                        endIndex = pids.length - 1;
                    }
                    // 获取pid集合
                    List<Long> pidList = new ArrayList<>();
                    for (int i = startIndex; i <= endIndex; i++) {
                        pidList.add(Long.valueOf(pids[i]));
                    }
                    // 调用mongodb查询动态
                    List<Publish> publishList = this.quanZiApi.queryPublishByPids(pidList);
                    pageInfo = new PageInfo<>();
                    pageInfo.setRecords(publishList);
                }
            }
        }
        if (null == pageInfo) {
            // redis推荐为空时走这个
            pageInfo = this.quanZiApi.queryPublishList(userId, page, pageSize);
        }

        pageResult.setPagesize(pageSize);
        pageResult.setPage(page);
        pageResult.setCounts(0);
        pageResult.setPages(0);

        //根据查询得到的pageinfo放入这里   records中存放的为：发布的publish
        List<Publish> records = pageInfo.getRecords();

        //判断得到的数据是否为空
        if (CollectionUtils.isEmpty(records)) {
            //没有动态信息
            return pageResult;
        }

        /*// 创建动态保存对象
        List<Movements> movementsList = new ArrayList<>();
        for (Publish record : records) {
            Movements movements = new Movements();

            movements.setId(record.getId().toHexString());
            movements.setImageContent(record.getMedias().toArray(new String[]{}));
            movements.setTextContent(record.getText());
            movements.setUserId(record.getUserId());
            movements.setCreateDate(RelativeDateFormat.format(new Date(record.getCreated())));

            movementsList.add(movements);
        }

        List<Long> userIds = new ArrayList<>();
        for (Movements movements : movementsList) {
            if(!userIds.contains(movements.getId())){
                // 把userId赋值给集合，后面需要查用户信息
                userIds.add(movements.getUserId());
            }

        }

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        List<UserInfo> userInfos = this.userInfoService.queryList(queryWrapper);
        for (Movements movements : movementsList) {
            for (UserInfo userInfo : userInfos) {
                if (movements.getUserId().longValue() == userInfo.getUserId().longValue()) {
                    movements.setAge(userInfo.getAge());
                    movements.setAvatar(userInfo.getLogo());
                    movements.setGender(userInfo.getSex().name().toLowerCase());
                    movements.setNickname(userInfo.getNickName());
                    movements.setTags(StringUtils.split(userInfo.getTags(), ','));

                    String userKey = "QUANZI_COMMENT_LIKE_USER_" + user.getId() + "_" + movements.getId();
                    movements.setHasLiked(this.redisTemplate.hasKey(userKey) ? 1 : 0); // 是否点赞（1是，0否）

                    //点赞数
                    String key = "QUANZI_COMMENT_LIKE_" + movements.getId();
                    String value = this.redisTemplate.opsForValue().get(key);
                    if(StringUtils.isNotEmpty(value)){
                        movements.setLikeCount(Integer.valueOf(value));
                    }else{
                        movements.setLikeCount(0);
                    }

                    //是否喜欢
                    String userLoveKey = "QUANZI_COMMENT_LOVE_USER_" + user.getId() + "_" + movements.getId();
                    movements.setHasLoved(this.redisTemplate.hasKey(userLoveKey) ? 1 : 0); // 是否喜欢（1是，0否）

                    //喜欢数
                    String keyLove = "QUANZI_COMMENT_LOVE_" + movements.getId();
                    String valueLove = this.redisTemplate.opsForValue().get(keyLove);
                    if(StringUtils.isNotEmpty(valueLove)){
                        movements.setLikeCount(Integer.valueOf(valueLove));
                    }else{
                        movements.setLoveCount(0);
                    }

                    movements.setCommentCount(10); //TODO 评论数
                    movements.setDistance("1.2公里"); //TODO 距离
                    break;
                }
            }
        }*/
        List<Movements> movementsList = fillValueToMovements(records);
        pageResult.setItems(movementsList);
        return pageResult;
    }


    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 点赞
     *
     * @param publishId
     * @return
     */
    public Long likeComment(String publishId) {
        // 获取用户信息
        User user = UserThreadLocal.get();
        // 调用接口实现点赞保存
        boolean bool = this.quanZiApi.saveLikeComment(user.getId(), publishId);
        // 点赞失败代表已经点过了
        if (!bool) {
            return null;
        }
        //点赞成功操作

        //设置总点赞数
        Long likeCount = 0L;

        //保存点赞数到redis

        String key = "QUANZI_COMMENT_LIKE_" + publishId;
        if (!this.redisTemplate.hasKey(key)) {   //如果没有点赞数，则赋值为1
            Long count = this.quanZiApi.queryCommentCount(publishId, 1);
            likeCount = count;
            this.redisTemplate.opsForValue().set(key, String.valueOf(likeCount));
        } else {
            // 有点赞则读取后自增
            likeCount = this.redisTemplate.opsForValue().increment(key);
        }

        //记录已点赞  记录该用户已经点过赞？？有什么意义   movemrnts中的用户是否喜欢是否点赞
        String userKey = "QUANZI_COMMENT_LIKE_USER_" + user.getId() + "_" + publishId;
        this.redisTemplate.opsForValue().set(userKey, "1");

        return likeCount;
    }

    /**
     * 取消点赞
     *
     * @return
     */
    public Long cancelLikeComment(String publishId) {
        User user = UserThreadLocal.get();
        boolean bool = this.quanZiApi.removeComment(user.getId(), publishId, 1);
        if (bool) {
            String key = "QUANZI_COMMENT_LIKE_" + publishId;

           /*    负数bug// 点赞总数
            Long likeCount = 0L;
            // 判断点赞量
            if(Integer.valueOf(this.redisTemplate.opsForValue().get(key)) < 1){
                this.redisTemplate.opsForValue().set(key, String.valueOf(likeCount));
            }else{
                //数量递减
                likeCount = this.redisTemplate.opsForValue().decrement(key);
            }*/


            Long likeCount = this.redisTemplate.opsForValue().decrement(key);

            //删除已点赞
            String userKey = "QUANZI_COMMENT_LIKE_USER_" + user.getId() + "_" + publishId;
            this.redisTemplate.delete(userKey);

            return likeCount;
        }
        return null;
    }


    /**
     * 喜欢
     *
     * @param publishId
     * @return
     */
    public Long loveComment(String publishId) {
        User user = UserThreadLocal.get();
        boolean bool = this.quanZiApi.saveLoveComment(user.getId(), publishId);
        if (!bool) {
            return null;
        }

        Long loveCount = 0L;

        //保存喜欢数到redis
        String key = "QUANZI_COMMENT_LOVE_" + publishId;
        if (!this.redisTemplate.hasKey(key)) {
            Long count = this.quanZiApi.queryCommentCount(publishId, 3);
            loveCount = count;
            this.redisTemplate.opsForValue().set(key, String.valueOf(loveCount));
        } else {
            loveCount = this.redisTemplate.opsForValue().increment(key);
        }

        //记录已喜欢
        String userKey = "QUANZI_COMMENT_LOVE_USER_" + user.getId() + "_" + publishId;
        this.redisTemplate.opsForValue().set(userKey, "1");

        return loveCount;
    }

    /**
     * 取消喜欢
     *
     * @return
     */
    public Long cancelLoveComment(String publishId) {
        User user = UserThreadLocal.get();
        boolean bool = this.quanZiApi.removeComment(user.getId(), publishId, 3);
        if (bool) {
            String key = "QUANZI_COMMENT_LOVE_" + publishId;
            //数量递减
            Long loveCount = this.redisTemplate.opsForValue().decrement(key);

            //删除已点赞
            String userKey = "QUANZI_COMMENT_LOVE_USER_" + user.getId() + "_" + publishId;
            this.redisTemplate.delete(userKey);

            return loveCount;
        }
        return null;
    }

    /**
     * 查询单条动态
     *
     * @param publishId
     * @return
     */
    public Movements queryById(String publishId) {
        Publish publish = this.quanZiApi.queryPublishById(publishId);
        if (null == publish) {
            return null;
        }
        List<Publish> list = new ArrayList<>();
        list.add(publish);
        List<Movements> movementsList = fillValueToMovements(list);
        return movementsList.get(0);
    }


    // 抽取方法，获取movements
    private List<Movements> fillValueToMovements(List<Publish> records) {
        // 获取user
        User user = UserThreadLocal.get();
        // 创建动态保存对象
        List<Movements> movementsList = new ArrayList<>();
        for (Publish record : records) {
            Movements movements = new Movements();

            movements.setId(record.getId().toHexString());
            movements.setImageContent(record.getMedias().toArray(new String[]{}));
            movements.setTextContent(record.getText());
            movements.setUserId(record.getUserId());
            movements.setCreateDate(RelativeDateFormat.format(new Date(record.getCreated())));

            movementsList.add(movements);
        }

        List<Long> userIds = new ArrayList<>();
        for (Movements movements : movementsList) {
            if (!userIds.contains(movements.getId())) {
                // 把userId赋值给集合，后面需要查用户信息
                userIds.add(movements.getUserId());
            }

        }

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        List<UserInfo> userInfos = this.userInfoService.queryList(queryWrapper);
        for (Movements movements : movementsList) {
            for (UserInfo userInfo : userInfos) {
                if (movements.getUserId().longValue() == userInfo.getUserId().longValue()) {
                    movements.setAge(userInfo.getAge());
                    movements.setAvatar(userInfo.getLogo());
                    movements.setGender(userInfo.getSex().name().toLowerCase());
                    movements.setNickname(userInfo.getNickName());
                    movements.setTags(StringUtils.split(userInfo.getTags(), ','));

                    String userKey = "QUANZI_COMMENT_LIKE_USER_" + user.getId() + "_" + movements.getId();
                    movements.setHasLiked(this.redisTemplate.hasKey(userKey) ? 1 : 0); // 是否点赞（1是，0否）

                    //点赞数
                    String key = "QUANZI_COMMENT_LIKE_" + movements.getId();
                    String value = this.redisTemplate.opsForValue().get(key);
                    if (StringUtils.isNotEmpty(value)) {
                        movements.setLikeCount(Integer.valueOf(value));
                    } else {
                        movements.setLikeCount(0);
                    }

                    //是否喜欢
                    String userLoveKey = "QUANZI_COMMENT_LOVE_USER_" + user.getId() + "_" + movements.getId();
                    movements.setHasLoved(this.redisTemplate.hasKey(userLoveKey) ? 1 : 0); // 是否喜欢（1是，0否）

                    //喜欢数
                    String keyLove = "QUANZI_COMMENT_LOVE_" + movements.getId();
                    String valueLove = this.redisTemplate.opsForValue().get(keyLove);
                    if (StringUtils.isNotEmpty(valueLove)) {
                        movements.setLoveCount(Integer.valueOf(valueLove));
                    } else {
                        movements.setLoveCount(0);
                    }

                    movements.setCommentCount(10); //TODO 评论数
                    movements.setDistance("1.2公里"); //TODO 距离
                    break;
                }
            }
        }
        return movementsList;
    }

    @Reference(version = "1.0.0")
    private VisitorsApi visitorsApi;

    /**
     * 谁看过我
     *
     * @return
     */
    public List<VisitorsVo> queryVisitorsList() {
        User user = UserThreadLocal.get();  //登录用户
        String redisKey = "visitor_date_" + user.getId();  // 存入redis中的key

        // 如果redis中存在上次查询的时间，就按照这个时间之后查询，如果没有就查询前5个
        List<Visitors> visitors = null;
        String value = this.redisTemplate.opsForValue().get(redisKey);  // todo 什么时候存入过这个数据？
        // 测试使用，先给个null
        value = null;
        if (StringUtils.isEmpty(value)) {
            visitors = this.visitorsApi.topVisitor(user.getId(), 5);
        } else {
            // 如果有就按事件查询返回
            visitors = this.visitorsApi.topVisitor(user.getId(), Long.valueOf(value));
        }

        if (CollectionUtils.isEmpty(visitors)) {
            return Collections.emptyList();
        }

        // 访客id集
        List<Long> userIds = new ArrayList<>();
        for (Visitors visitor : visitors) {
            userIds.add(visitor.getVisitorUserId());
        }

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        // 访客基本信息集
        List<UserInfo> userInfoList = this.userInfoService.queryList(queryWrapper);
        //返回访客信息集
        List<VisitorsVo> visitorsVoList = new ArrayList<>();

        for (Visitors visitor : visitors) {
            for (UserInfo userInfo : userInfoList) {
                if (visitor.getVisitorUserId().longValue() == userInfo.getUserId().longValue()) {

                    VisitorsVo visitorsVo = new VisitorsVo();
                    visitorsVo.setAge(userInfo.getAge());
                    visitorsVo.setAvatar(userInfo.getLogo());
                    visitorsVo.setGender(userInfo.getSex().name().toLowerCase());
                    visitorsVo.setId(userInfo.getUserId());
                    visitorsVo.setNickname(userInfo.getNickName());
                    visitorsVo.setTags(StringUtils.split(userInfo.getTags(), ','));
                    visitorsVo.setFateValue(visitor.getScore().intValue());

                    visitorsVoList.add(visitorsVo);
                    break;
                }
            }
        }

        return visitorsVoList;
    }


    /**
     * 查询个人所有动态
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryAlbumList(Long userId, Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        pageResult.setPages(0);
        pageResult.setCounts(0);
        PageInfo<Publish> albumPageInfo = this.quanZiApi.queryAlbumList(userId, page, pageSize);
        List<Publish> records = albumPageInfo.getRecords();

        if(CollectionUtils.isEmpty(records)){
            return pageResult;
        }
        List<Movements> movementsList = this.fillValueToMovements(records);
        pageResult.setItems(movementsList);
        return pageResult;
    }
}
